# -*- coding: utf-8 -*-
"""
百度文本审核
"""
from __future__ import print_function, unicode_literals
import requests
from logger_utility.loggconfig import getLogger

URL = "https://aip.baidubce.com/rest/2.0/antispam/v1/spam?access_token=24.661f60c91607c23208afc67666e5d844.2592000.1517982181.282335-10645273"
logger = getLogger("BaiduSpam")


def process(content):
    """
    进行调用
    :param content:
    :return:
    """
    data = {
        'command_no': 500071,
        'content': content
    }
    ret = None

    try:
        ret = requests.post(URL, data=data)
        ret_dict = ret.json()
        if ret_dict.get('errno') != 0:
            logger.warning('Query Baidu Spam Error, errno: %s', ret_dict.get('errno'))
            return ret_dict

        result_info = info_ret(ret_dict)
        ret_dict['info'] = result_info
        return ret_dict

    except Exception as e:
        logger.exception("Query Baidu Spam Exception, E: %s", e)
        return {
            'errno': -10,
            'e': str(e),
            'ret': ret.content if ret else ''
        }


Mapper = {
    'spam': {
        0: '非违禁',
        1: '违禁',
        2: '建议人工复审'
    },
    'type': {
        1: '文本色情',
        2: '文本含号码推广',
        3: '文本含url推广',
        4: '文本推广',
        5: '文本命中政治、辱骂、暴恐'
    },
    'labels': {
        1: '暴恐违禁',
        2: '文本色情',
        3: '政治敏感',
        4: '恶意推广',
        5: '低俗辱骂'
    }
}


def info_ret(ret):
    """
    对返回的结果进行细致的解析为中文
    :param ret:
    :return:
    """
    result = ret['result']
    new_result = {}
    if result:
        spam = result.get('spam')
        if spam:
            new_result['spam'] = Mapper['spam'].get(spam)

        type_ = result.get('type')
        if type_:
            new_result['old_type'] = Mapper['type'].get(type_)
        types = result.get('types')
        if types:
            new_result['old_types'] = []
            for i in types:
                new_result['old_types'].append(Mapper['type'].get(i))

        labels = result.get('labels')
        if labels:
            new_result['new_labels'] = []
            for i in labels:
                new_result['new_labels'].append(Mapper['labels'].get(i))

    return new_result


if __name__ == '__main__':
    import json
    print(json.dumps(process('日你妈妈'), ensure_ascii=False, indent=2))